import { EditModal } from '@ycx/ui';
import { useTheme } from '@/store/settingsStore.ts';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { App, DatePicker, Form, Input, UploadFile } from 'antd';
import { Dayjs } from 'dayjs';
import UploadImage from '@/components/UploadImage';
import { useMutation } from '@tanstack/react-query';
import WorkOrderServices from '@/api/services/workOrderServices.ts';
import FileServices, { FileInfo } from '@/api/services/fileServices.ts';

interface FormInstance {
  date: [Dayjs, Dayjs];
  handleTime: string;
  notes: string;
  fileIdList: UploadFile[];
}

export interface EditOrderStatusModalRef {
  open: (args: { id: number; date: FormInstance['date'] }) => void;
}

type Props = {
  onSuccess: () => void;
};

const EditOrderStatusModal = forwardRef<EditOrderStatusModalRef, Props>(({ onSuccess }, ref) => {
  const { message } = App.useApp();
  const theme = useTheme();
  const [open, setOpen] = useState(false);
  const orderId = useRef<number>();

  const [form] = Form.useForm<FormInstance>();

  const { mutate: reportHandleResult } = useMutation({
    mutationFn: WorkOrderServices.reportHandleResult,
    onSuccess: () => {
      message.success('上报成功');
      close();
      onSuccess();
    },
    onError: (error) => message.error(error.message),
  });

  const { mutate: addFile } = useMutation({
    mutationFn: FileServices.addFile,
    onSuccess: async ({ data }) => {
      await form.validateFields();
      const formData = form.getFieldsValue();
      const fileIdList = data.map((i) => i.id);

      reportHandleResult({
        fileIdList,
        id: orderId.current!,
        handleTime: formData.handleTime,
        notes: formData.notes,
      });
    },
    onError: (error) => message.error(error.message),
  });

  const handleSubmit = async () => {
    await form.validateFields();
    const formData = form.getFieldsValue();
    const fileList = formData.fileIdList.map<FileInfo>((i) => {
      return {
        fileType: i.type!,
        fileName: i.name!,
        fileSize: i.size!,
        fileUrl: i.url!.split('https://oss.uconcern.com/')[1],
      };
    });
    addFile(fileList);
  };

  const close = () => {
    setOpen(false);
    form.resetFields();
    orderId.current = undefined;
  };

  useImperativeHandle(ref, () => ({
    open: ({ id, date }) => {
      orderId.current = id;
      form.setFieldValue('date', date);
      setOpen(true);
    },
  }));

  return (
    <EditModal
      width={600}
      title="上报处置结果"
      theme={theme}
      open={open}
      onClose={close}
      onCancel={close}
      onOk={handleSubmit}
      modalRender={(dom) => (
        <Form form={form} layout="vertical" initialValues={{ userBlock: false }}>
          {dom}
        </Form>
      )}
    >
      <Form.Item label="计划完成时间" name="date">
        <DatePicker.RangePicker disabled={true} />
      </Form.Item>
      <Form.Item
        label="完成时间"
        name="handleTime"
        rules={[{ required: true, message: '请选择完成时间' }]}
      >
        <DatePicker></DatePicker>
      </Form.Item>
      <Form.Item
        label="现场照片"
        name="fileIdList"
        rules={[{ required: true, message: '请上传至少一张现场照片' }]}
      >
        <UploadImage maxCount={3} />
      </Form.Item>
      <Form.Item label="情况说明" name="notes">
        <Input.TextArea />
      </Form.Item>
    </EditModal>
  );
});

export default EditOrderStatusModal;
